package com.project.web.system.service.impl.app;

import com.project.web.system.mapper.app.AdminRoleMapper;
import com.project.web.system.mapper.app.MenuMapper;
import com.project.web.system.mapper.app.RoleMenuMapper;
import com.project.web.system.model.app.Menu;
import com.project.web.system.service.app.MenuService;
import com.project.web.system.service.impl.common.BaseServiceImpl;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName MenuServiceImpl
 * @Description
 * @Author 王天豪
 * @Date 2020/8/14 10:32 AM
 * @Version 1.0
 */
@Service("menuServiceImpl")
public class MenuServiceImpl extends BaseServiceImpl<Menu,Long> implements MenuService {


    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private AdminRoleMapper adminRoleMapper;

    @Autowired
    private RoleMenuMapper roleMenuMapper;



    @Override
    public List<Menu> findChildrenNodes(Long id) {
        return menuMapper.getTree(id);
    }

    @Override
    public List<Menu> selectMenu(Long userId) {
        List<Long> roles = adminRoleMapper.selectRoleByUserId(userId);
        if(CollectionUtils.isNotEmpty(roles)){
            List<Long> menuids = roleMenuMapper.selectMenuByRoleIds(roles);
            List<Menu> menus = menuMapper.getMenuByMenuIds(menuids);
            for (Menu m : menus) {
                for (int i = m.getChildren().size() - 1; i >= 0; i--) {
                    Menu children = m.getChildren().get(i);
                    boolean contains = menuids.contains(children.getId());
                    if (!contains) {
                        m.getChildren().remove(i);
                        continue;
                    }
                    children.setChildren(null);
                }
            }
            return menus;
        }
        return null;
    }

    @Override
    public List<Menu> selectButtonMenu(Long userId) {
        List<Long> roles = adminRoleMapper.selectRoleByUserId(userId);
        List<Long> menuids = roleMenuMapper.selectMenuByRoleIds(roles);
        List<Menu> menus = menuMapper.selectBottonMenu(menuids);
        return menus;
    }

}
